/*
 * Copyright 2012 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.fujitsu.nanjing.tieba.base.BaseService;
import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.ibator.CoreAttach;
import com.fujitsu.nanjing.tieba.ibator.CoreBoard;
import com.fujitsu.nanjing.tieba.ibator.CoreReply;
import com.fujitsu.nanjing.tieba.ibator.CoreReplyCriteria;
import com.fujitsu.nanjing.tieba.ibator.CoreReportLog;
import com.fujitsu.nanjing.tieba.ibator.CoreTopic;
import com.fujitsu.nanjing.tieba.ibator.CoreTrashBox;
import com.fujitsu.nanjing.tieba.model.Reply;
import com.fujitsu.nanjing.tieba.struct.FileStruct;

/**
 * ReplyService.java
 * 
 * @author Qixiaobo-win8
 */
@Service
@Transactional
public class ReplyService extends BaseService<CoreReply, CoreReplyCriteria> {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ReplyService.class);

	@Autowired
	private Reply reply;
	@Resource
	private AttachService attachService;
	@Resource
	private UserService userService;
	@Resource
	private TopicService topicService;
	@Resource
	private TrashBoxService trashBoxService;
	@Resource
	private BoardService boardService;
	@Resource
	private ReportLogService reportLogService;
	@Override
	public CoreReply findById(String id) {
		return reply.selectByPrimaryKey(Integer.parseInt(id));
	}

	@Override
	public CoreReply insert(CoreReply t) {
		initReply(t);
		reply.insertSelective(t);
		userService.updateUserPosts(t.getUserid());
		return t;
	}

	private void initReply(CoreReply t) {
		t.setCreatetime(new Date());
	}

	@Override
	public void update(CoreReply t) {
		reply.updateByPrimaryKeySelective(t);

	}

	@Override
	public void delete(CoreReply t) {
		recycle(t);
		// reply.deleteByPrimaryKey(t.getReplyid());
		t.setState(CommonParamter.删除帖子);
		update(t);
		topicService.deleteReply(t.getTopicid().toString());

	}
	/**
	 * 此方法为回收回复，最好不要调用，有友元就好了
	 * */
	public void recycle(CoreReply t) {
		CoreTrashBox trashBox = new CoreTrashBox();
		trashBox.setTopicid(t.getTopicid());
		trashBox.setReplyid(t.getReplyid());
		trashBox.setCreatetime(new Date());
		trashBox.setTopictitle(t.getTitle());
		CoreTopic topic = topicService.findById(String.valueOf(t.getTopicid()));
		CoreBoard board = boardService.findById(topic.getBoardid().toString());
		trashBox.setBoardname(board.getBoardname());
		trashBox.setBoardid(topic.getBoardid());
		trashBox.setDeleteuser(getUserDetails().getUsername());
		trashBox.setUserid(t.getUserid());
		trashBoxService.insert(trashBox);

	}

	public List<CoreReply> findRepliesByTopicId(int topicId, int offset) {
		CoreReplyCriteria example = new CoreReplyCriteria();
		example.setMysqlLength(CommonParamter.默认分页长度);
		if (offset > 0) {
			example.setMysqlOffset((offset - 1) * CommonParamter.默认分页长度);
		}
		example.setOrderByClause(CommonParamter.默认回复排序条件);
		example.createCriteria().andTopicidEqualTo(topicId)
				.andStateNotEqualTo(CommonParamter.删除帖子);
		return reply.selectByExampleWithBLOBs(example);
	}
	public List<CoreReply> findRepliesByTopicId(int topicId) {
		CoreReplyCriteria example = new CoreReplyCriteria();
		example.createCriteria().andTopicidEqualTo(topicId)
				.andStateNotEqualTo(CommonParamter.删除帖子);
		return reply.selectByExampleWithBLOBs(example);
	}
	public int countRepliesByBoardId(int boardId) {
		return reply.countRepliesByBoardId(boardId);
	}

	public List<CoreReply> findRepliesByUserId(String userId, int offset) {
		CoreReplyCriteria example = new CoreReplyCriteria();
		example.setMysqlLength(CommonParamter.默认分页长度);
		if (offset > 0) {
			example.setMysqlOffset((offset - 1) * CommonParamter.默认分页长度);
		}
		example.setOrderByClause(CommonParamter.默认排序条件);
		example.createCriteria().andUseridEqualTo(userId)
				.andStateNotEqualTo(CommonParamter.删除帖子);
		return reply.selectByExampleWithBLOBs(example);
	}

	public int countByUserId(String userId) {
		CoreReplyCriteria example = new CoreReplyCriteria();
		example.createCriteria().andUseridEqualTo(userId);
		return reply.countByExample(example);
	}
	/**
	 * 根据用户获取主题总页数
	 * */
	public int findPageCountByUserId(String userId) {
		int pageCount = (int) Math.ceil((double) countByUserId(userId)
				/ CommonParamter.默认分页长度);
		if (pageCount == 0) {
			pageCount = 1;
		}
		return pageCount;
	}

	public int insertWithAttaches(CoreReply t, List<FileStruct> fileStructs) {
		insert(t);
		for (FileStruct fileStruct : fileStructs) {
			insertAttach(fileStruct, t);
		}
		return t.getReplyid();

	}
	public int countReplies() {
		return reply.countReplies();
	}

	public void updateWithAttaches(CoreReply reply, List<FileStruct> fileStructs) {
		attachService.deleteByReplyId(reply.getReplyid());
		update(reply);
		for (FileStruct fileStruct : fileStructs) {
			insertAttach(fileStruct, reply);
		}

	}
	public void insertAttach(FileStruct fileStruct, CoreReply t) {
		CoreAttach coreAttach = new CoreAttach();
		MultipartFile file = fileStruct.getFile();
		if (file.getContentType().startsWith("image")) {
			logger.info("上传图片：" + file.getOriginalFilename());
		} else {
			logger.info("上传文件：" + file.getOriginalFilename());
		}
		coreAttach.setFilename(file.getOriginalFilename());
		coreAttach.setTopicid(t.getTopicid());
		coreAttach.setTitle(fileStruct.getTitle());
		coreAttach.setUserid(t.getUserid());
		coreAttach.setCredits(fileStruct.getCredits());
		coreAttach.setFilesize((int) file.getSize());
		// 产生随机的名字
		String tempName = String.valueOf(System.nanoTime())
				+ file.getOriginalFilename().substring(
						file.getOriginalFilename().lastIndexOf("."));
		coreAttach.setLocalname(tempName);
		coreAttach.setReplyid(t.getReplyid());
		coreAttach.setLocalid((short) fileStruct.getLocalid());
		// 将文件写入upload目录下
		File dest = new File(CommonParamter.webRoot + CommonParamter.uploadPath
				+ File.separatorChar + tempName);
		try {
			file.transferTo(dest);
		} catch (IllegalStateException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		attachService.insert(coreAttach);
	}
	public void reportReply(CoreReply coreReply, int boardid, Date now,
			String reason, String username) {
		CoreReportLog t = new CoreReportLog();
		t.setBoardid(boardid);
		t.setBoardname(boardService.findById(String.valueOf(boardid))
				.getBoardname());
		t.setCreatetime(now);
		t.setReason(reason);
		t.setReplyid(0);
		t.setTopicid(coreReply.getTopicid());
		t.setReporteduser(coreReply.getUserid());
		t.setTopictitle(coreReply.getTitle());
		t.setUserid(username);
		reportLogService.insert(t);

	}
	public int countMonthNewReplies() {
		return reply.countMonthNewReplies();
	}
	public List<CoreReply> findBest4Topic(int topicId) {
		CoreReplyCriteria example = new CoreReplyCriteria();
		example.createCriteria().andTopicidEqualTo(topicId)
				.andStateNotEqualTo(CommonParamter.删除帖子).andIsbestEqualTo("T");
		return reply.selectByExampleWithoutBLOBs(example);
	}
}
